import { errorReport } from '../utils/tools';
import { InitSDK, type Ability } from '@vtuber/ThreeSDK';
import type { HumanInfo, SdkInitData } from '../types/vtuber';

export default () => {
  // 是否初始化完成
  let initResult: boolean = false;
  // 引擎实例
  let engine: Ability | void;
  // 初始化sdk的内容
  let sdkInitData: SdkInitData = {
    appSecret: '',
    appId: '',
    baseUrl: '',
    userId: ''
  };
  // canvas的dom
  let canvasRef: HTMLCanvasElement | void;
  // 传入需要使用第几个虚拟人
  let vtuberIndex: number = 0;
  // 虚拟人配置信息
  let humanInfo: HumanInfo = {
    canRotate: false,
    canScale: false,
    humanClassName: '',
    lightClass: '',
    stageClass: '',
    distance: 5
  };
  // 初始化虚拟人引擎
  const initEngine = (
    canvasRef: HTMLCanvasElement | void,
    sdkInitData: SdkInitData
  ): Promise<void | Ability> => {
    if (!canvasRef) {
      return Promise.reject('canvas没有渲染出来');
    }
    console.log(sdkInitData.appSecret, sdkInitData.appId, sdkInitData.baseUrl);
    console.log(InitSDK);
    
    const sdk = new InitSDK(sdkInitData.appSecret, sdkInitData.appId, sdkInitData.baseUrl);
    // 虚拟人sdk如果使用了nginx转发，必须要在initsdk和initengine之间加上此参数
    window.isPlatform = true;
    return sdk
      .initEngine({
        canvas: canvasRef,
        wsBaseUrl: '',
        errorCallback: (e) => {
          console.error(e);
          errorReport({
            name: `sdk初始化引擎时发生错误sdk.initEngine ${e?.name}`,
            message: e?.message,
            stack: e?.stack
          });
        },
        openQueue: true
      })
      .catch((e) => {
        errorReport({
          name: `sdk初始化引擎时发生错误sdk.initEngine ${e?.name}`,
          message: e?.message,
          stack: e?.stack
        });
      });
  };
  // 获取虚拟人列表
  const setVtuber = (vtuberIndex: number, engine: Ability) =>
    engine
      .getVtuberList()
      .then((list) => engine.createVtuberById(list[vtuberIndex].id, false))
      .catch((error) => {
        errorReport({
          name: `获取虚拟人列表时发生错误engine.getVtuberList ${error?.name}`,
          message: error?.message,
          stack: error?.stack
        });
      });

  // 改变虚拟人信息
  const changeHumanInfo = (humanInfo: HumanInfo, engine: Ability) => {
    try {
      engine.changeCameraInfo({
        canZoom: humanInfo.canScale,
        distance: humanInfo.distance
      });
      engine.changeHumanInfo(humanInfo);
    } catch (error) {
      errorReport({
        name: `改变虚拟人信息发生错误 changeCameraInfo changeHumanInfo ${error?.name}`,
        message: error?.message,
        stack: error?.stack
      });
    }
  };

  return {
    initResult,
    sdkInitData,
    canvasRef,
    vtuberIndex,
    humanInfo,
    engine,
    initEngine,
    setVtuber,
    changeHumanInfo
  };
};
